package com.app.twth.ui.adjust.redamage.oldsku;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.base.BaseCameraPhotoActivity;
import com.app.twth.bean.FilePathListDTO;
import com.app.twth.bean.PhotoBean;
import com.app.twth.databinding.ActivityRedamageOldSkuBinding;
import com.app.twth.databinding.DialogRedamageDetailBinding;
import com.app.twth.ui.adjust.redamage.ReDamage;
import com.app.twth.ui.adjust.redamage.ReDamageAdapter;
import com.app.twth.ui.adjust.redamage.ReDamageQr;
import com.app.twth.ui.b2cpick.submit.SKUBarcodes;
import com.app.twth.ui.checkin.PhotoAdapter;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.ToastUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class RDOldSkuActivity extends BaseCameraPhotoActivity<ActivityRedamageOldSkuBinding, RDOldSkuViewModel> {
    private String TAG = getClass().getSimpleName();
    private int type = 0;
    private int position = 0;
    private ReDamage reDamage;
    private ReDamageQr reDamageQr;
    private List<PhotoBean> photo1Paths = new ArrayList<>();
    private PhotoAdapter photo1Adapter;

    @Override
    protected String setTitle() {
        return "Damage";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setNext(getString(R.string.submit));

        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        reDamage = (ReDamage) bundle.getSerializable("data");
        reDamageQr = (ReDamageQr) bundle.getSerializable("ReDamageQr");

        binding.tvContaier.setText(reDamage.getContainerNo());
        binding.tvIblpn.setText(reDamage.getLpn());
        binding.tvSkuQuantity.setText(reDamage.getSku() + "(" + reDamage.getQty() + ")");
        binding.tvCodeLocation.requestFocus();

        if (reDamage.getType() == 6) {//换SKU
            binding.tvCodeLpn.setHint("scan new inbound lpn barcode");
            binding.layoutCodeSku.setVisibility(View.GONE);
            binding.layoutCtn.setVisibility(View.GONE);
            binding.tvSkuQuantity.setText(reDamage.getNewSku() + "(" + reDamage.getQty() + ")");
        } else {
            binding.tvSkuQuantity.setText(reDamage.getSku() + "(" + reDamage.getQty() + ")");
        }

        photo1Paths.add(new PhotoBean());
        photo1Adapter = new PhotoAdapter(this, photo1Paths, 0, position -> {
            this.position = position;
            requestCamera("photo1");
        }, str -> {
        });
        GridLayoutManager photo1Manager = new GridLayoutManager(this, 3);
        binding.rvPhoto1.setLayoutManager(photo1Manager);
        binding.rvPhoto1.setAdapter(photo1Adapter);

        binding.tvCodeLocation.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCodeLpn.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvCodeSku.setOnFocusChangeListener(onFocusChangeListener);
        binding.tvQty.setOnFocusChangeListener(onFocusChangeListener);

        binding.tvCodeSku.setOnEditorActionListener(EnterListenter);
        binding.tvCodeSku.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.skuBarcodesLiveData.setValue(null);
                binding.tvQty.setText("");
            }
        });

        if ((reDamage.getProcessList() == null) || (reDamage.getProcessList().size() == 0)) {
            binding.ivSkuQuantity.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initListener() {
        viewModel.skuBarcodesLiveData.observe(this, data -> {
            binding.tvQty.setText("1");
            binding.tvQty.requestFocus();
        });
        viewModel.fileUploadMutableLiveData.observe(this, data -> {
            Log.e(TAG, "type():" + data.getType() + ",position:" + data.getPosition());
            if (photo1Paths.size() > data.getPosition()) {
                PhotoBean photoBean = photo1Paths.get(data.getPosition());
                photoBean.setUrlImg(data.getPath());
            }

            if (data.isSubmit()) {
                submitData();
            }
        });
        viewModel.lpnPhotoSubmitMutableLiveData.observe(this, data -> {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        showHint("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_sku:
                if (reDamage.getProcessList() == null) {
                    return;
                }
                if (reDamage.getProcessList().size() == 0) {
                    return;
                }
                showReDamageDetailDialog();
                break;
            case R.id.iv_scan_location:
                type = 0;
                setScan();
                break;
            case R.id.iv_scan_lpn:
                type = 1;
                setScan();
                break;
            case R.id.iv_scan_sku:
                type = 2;
                setScan();
                break;
            case R.id.iv_qty:
                String cartonsQty = binding.tvQty.getText().toString();
                if (Utils.isEmpty(cartonsQty)) {
                } else if (Integer.parseInt(cartonsQty) > 1) {
                    binding.tvQty.setText((Integer.parseInt(cartonsQty) - 1) + "");
                } else {
                    binding.tvQty.setText("0");
                }
                break;
            case R.id.tv_reset:
                binding.tvCodeLocation.setText("");
                binding.tvCodeLpn.setText("");
                binding.tvCodeSku.setText("");
                binding.tvQty.setText("");
                showHint("");
                break;
            case R.id.tv_next:
                submitData();
                break;
        }
    }

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                type = 0;
                return;
            }

            switch (v.getId()) {
                case R.id.tv_code_location:
                    type = 0;
                    break;
                case R.id.tv_code_lpn:
                    type = 1;
                    break;
                case R.id.tv_code_sku:
                    type = 2;
                    break;
                case R.id.tv_qty:
                    type = 3;
                    break;
            }
        }
    };

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCodeSku.getText().toString();
                EditTextUtil.hideInput(mContext);
                bottomLayoutBinding.tvHint.setText("");
                if (!Utils.isEmpty(barcodeStr)) {
                    viewModel.getInfoByBarcode(barcodeStr);
                    binding.tvQty.setText("");
                }
            }
            return false;
        }
    };

    @Override
    public void getScanninCode() {
        super.getScanninCode();
        switch (type) {
            case 0:
                binding.tvCodeLocation.setText(barcodeStr);
                binding.tvCodeLpn.requestFocus();
                break;
            case 1:
                binding.tvCodeLpn.setText(barcodeStr);
                binding.tvCodeSku.requestFocus();
                break;
            case 2:
                viewModel.getInfoByBarcode(barcodeStr);
                binding.tvCodeSku.setText(barcodeStr);
                binding.tvQty.setText("");
                break;
            case 3:
                try {
                    String barCode = binding.tvCodeSku.getText().toString();
                    if (Utils.isEmpty(barCode)) {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        return;
                    }
                    Log.e(TAG, "barCode:" + barCode);
                    Log.e(TAG, "barcodeStr:" + barcodeStr);
                    SKUBarcodes skuBarcodes = viewModel.skuBarcodesLiveData.getValue();
                    if (skuBarcodes == null) {
                        ToastUtil.showToast(getString(R.string.scan_inbound_lpn_lower));
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                        return;
                    }

                    if ((skuBarcodes.getBarcodeList() != null) && (skuBarcodes.getBarcodeList().size() > 0)) {
                        for (String barcode : skuBarcodes.getBarcodeList()) {
                            if (barCode.equalsIgnoreCase(barcode)) {
                                String qty = binding.tvQty.getText().toString();
                                if (Utils.isEmpty(qty)) {
                                    binding.tvQty.setText(1 + "");
                                    return;
                                } else {
                                    binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                                    return;
                                }
                            }
                        }
                    } else if (barCode.equalsIgnoreCase(barcodeStr)) {
                        String qty = binding.tvQty.getText().toString();
                        if (Utils.isEmpty(qty)) {
                            binding.tvQty.setText(1 + "");
                        } else {
                            binding.tvQty.setText((1 + Integer.parseInt(qty)) + "");
                        }
                    } else {
                        mVibrator.vibrate(new long[]{0, 1000}, -1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void getImgPath(String path) {
        setPath(path);
    }

    private void setPath(String pathImage) {
        Log.e(TAG, "setPath,pathImage:" + pathImage);
        if (!pathImage.contains("http")) {//选择的图片
            String fileName = "lpnphoto";
            viewModel.fileUpload(reDamage.getContainerNo(), fileName, pathImage, position, false, false);
        }
        PhotoBean imgUrl = new PhotoBean();
        imgUrl.setPathImg(pathImage);
        imgUrl.setUrlImg(pathImage);
        photo1Paths.add(position, imgUrl);

        if (!Utils.isEmpty(photo1Paths.get(photo1Paths.size() - 1).getPathImg())) {
            photo1Paths.add(new PhotoBean());
        }

        if (photo1Adapter != null) {
            photo1Adapter.setData(photo1Paths);
        }
    }

    private void submitData() {
        if (System.currentTimeMillis() - timeMillis < 2000) {
            return;
        }
        timeMillis = System.currentTimeMillis();

        String location = binding.tvCodeLocation.getText().toString();
        if (Utils.isEmpty(location)) {
            ToastUtil.showToast("Please enter the location");
            return;
        }

        String lpn = binding.tvCodeLpn.getText().toString();

        if (Utils.isEmpty(lpn)) {
            if (reDamage.getType() == 6) {//换SKU
                ToastUtil.showToast("Please enter the new lpn");
                return;
            }
            ToastUtil.showToast("Please enter the lpn");
            return;
        }
//        if (!lpn.equalsIgnoreCase(reDamage.getLpn())) {
//            ToastUtil.showToast("Invalid IBLPN,please rescan");
//            return;
//        }

        if (reDamage.getType() == 5) {//不换SKU
            String sku_barcode = binding.tvCodeSku.getText().toString();
            if (Utils.isEmpty(sku_barcode)) {
                ToastUtil.showToast("Please enter the SKU/Barcode");
                return;
            }

            String qtyStr = binding.tvQty.getText().toString();
            if (Utils.isEmpty(qtyStr)) {
                qtyStr = "0";
            }
            int qty = Integer.parseInt(qtyStr);
            if (qty != reDamage.getQty()) {//数量不等
                ToastUtil.showToast("errro：exceed QTY");
                return;
            }
        }

        List<String> lpnPathList = new ArrayList<>();
        if (photo1Paths.size() > 0) {
            for (int i = 0; i < photo1Paths.size(); i++) {
                PhotoBean photoBean = photo1Paths.get(i);
                String s = photoBean.getUrlImg();
                Log.e(TAG, "s:" + photoBean.toString());
                if (!Utils.isEmpty(s)) {
                    if (!s.contains("http")) {
                        position = i;
                        viewModel.fileUpload(reDamage.getContainerNo(), "photo1", s, position, true, true);
                        return;
                    }
                    lpnPathList.add(s);
                } else if (!Utils.isEmpty(photoBean.getPathImg())) {
                    position = i;
                    viewModel.fileUpload(reDamage.getContainerNo(), "photo1", photoBean.getPathImg(), position, true, true);
                    return;
                }
            }
        }
        if (lpnPathList.size() == 0) {
            ToastUtil.showToast("Please add lpn photos");
            return;
        }
        if (reDamageQr == null) {
            reDamageQr = new ReDamageQr();
        }

        reDamageQr.setTaskId(reDamage.getTaskId());
        reDamageQr.setLocation(location);
        List<FilePathListDTO> filePathList = new ArrayList<>();

        FilePathListDTO lpnFilePathListDTO = new FilePathListDTO();
        lpnFilePathListDTO.setName("lpnPhoto");
        lpnFilePathListDTO.setPathList(lpnPathList);
        filePathList.add(lpnFilePathListDTO);
        reDamageQr.setIbLpnPhoto(filePathList);

        viewModel.damageProcessSubmit(reDamageQr);
    }

    private AlertDialog dialogReDamageDetail;

    private void showReDamageDetailDialog() {
        dialogReDamageDetail = MyDialogUtil.getDialog(mContext, initReDamageDetailDialogView(), Gravity.CENTER);
        dialogReDamageDetail.setCanceledOnTouchOutside(true);
        dialogReDamageDetail.show();
    }

    ReDamageAdapter tallyDetailAdapter;

    private View initReDamageDetailDialogView() {
        DialogRedamageDetailBinding dialogBinding = DialogRedamageDetailBinding.inflate(getLayoutInflater());

        tallyDetailAdapter = new ReDamageAdapter(this, reDamage.getProcessList());

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerviewDetail.setLayoutManager(layoutManager1);
        dialogBinding.recyclerviewDetail.setAdapter(tallyDetailAdapter);

        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogReDamageDetail != null) {
                dialogReDamageDetail.dismiss();
            }
        });
        return dialogBinding.getRoot();
    }
}
